package com.xuebang.admin.web;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;

import com.google.common.base.Splitter;
import com.xuebang.admin.entity.Operator;
import com.xuebang.admin.service.OperatorService;

@Component
public class AuthenticateFilter implements Filter {
	
	@Inject
	private OperatorService operatorService;

	private Set<String> ignorePaths;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		ignorePaths = new HashSet<String>();
		String paths = filterConfig.getInitParameter("ignorePaths");
		if (paths != null) {
			for (String path : Splitter.on(",").split(paths)) {
				ignorePaths.add(path);
			}
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		String path = req.getRequestURI();
		if (ignorePaths.contains(path) || isLoginPath(path,req)||path.contains("/admin/upload/")) {
/*			HttpSession session =req.getSession();
			// 从共享session中取出来
	       ServletContext Context = session.getServletContext();   
	       ServletContext ContextAdmin= Context.getContext("/admin");     
	        if(ContextAdmin !=null && !ContextAdmin.equals("")){       
	            HttpSession sess =(HttpSession)ContextAdmin.getAttribute("sessionPic");
	            if(sess!=null){
	    			session.setAttribute("uid", sess.getAttribute("uid"));
	    			session.setAttribute("currentOperator", sess.getAttribute("currentOperator"));
	            }
	        }*/
			chain.doFilter(request, response);
		} else {
			HttpSession session = req.getSession(true);
			if(session.isNew()){
				goToLogin(resp,req);
				return;
			}
			Number uid = (Number)session.getAttribute("uid");
			if(uid==null){
			   ServletContext Context = session.getServletContext();   
		       ServletContext ContextAdmin= Context.getContext("/admin");     
		        if(ContextAdmin !=null && !ContextAdmin.equals("")){
		        	// 报session过期异常？
		        	try{
			        	HttpSession sess =(HttpSession)ContextAdmin.getAttribute("sessionPic");
			            if(sess!=null){
			            	uid = (Number)sess.getAttribute("uid");
			            }
		        	}catch(Exception e){
		        		e.printStackTrace();
		        		goToLogin(resp,req);
						return;
		        	}
		        }
			}

			if (uid == null) {
				goToLogin(resp,req);
				return;
			}

			Operator operator = operatorService.findById(uid.longValue());
			if (operator == null) {
				goToLogin(resp,req);
				return;
			}
			
			// 如果已经登录了，输入/admin 或者/admin/,则跳转到welcome页面
			if(path.equals("/admin")||path.equals("/admin/")){
				resp.sendRedirect("/admin/account/welcome");
				return;
			}
			// 放入共享session
			req.setAttribute("currentOperator", operator);
			session.setAttribute("uid", operator.getOperatorId());
			session.setAttribute("currentOperator", operator);
			// 存入session
			ServletContext contextA = session.getServletContext();
			contextA.setAttribute("sessionPic", session);
			chain.doFilter(request, response);
		}
	}

	private void goToLogin(HttpServletResponse resp,ServletRequest request) throws IOException {
		HttpServletRequest req = (HttpServletRequest) request;
		String contextPath =req.getContextPath();
		resp.sendRedirect(contextPath+"/account/login");
	}

	private boolean isLoginPath(String path,ServletRequest request) {
		HttpServletRequest req = (HttpServletRequest) request;
		String contextPath =req.getContextPath()+"/account/login";
		return contextPath.equals(path);
	}

	@Override
	public void destroy() {
	}

}
